package com.baseweb.webadmin.weixin.pay;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import com.baseweb.webadmin.weixin.utils.Constant;
import com.baseweb.webadmin.weixin.utils.HttpGetOrPost;

/**
 *根据用户的code获取openid
 *存入session  
 */
public class GetOpenid extends HttpServlet {
	private   static  Logger logeer = LoggerFactory.getLogger(GetOpenid.class);
	private static final long serialVersionUID = 1L;
       
  
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//进行页面授权 获取用户唯一标识 openid
		logeer.info("微信认证后回调:code--->"+request.getParameter("code"));
	    String openid =	getOpenid(request.getParameter("code"));
	    logeer.info("微信认证后回调 GetOpenid  sessionId"+request.getSession().getId());
	    request.getSession().setAttribute(Constant.OPENID, openid);
	    //request.getRequestDispatcher("/shoop.jsp").forward(request, response); (String) request.getSession().getAttribute("linkSource")
	    response.sendRedirect("/weixin/jsp/login.jsp");
	}
	
	public String getOpenid(String userCode) {
		 logeer.info("GetOpenid  start");
		StringBuffer getAccessTokenUrl = new StringBuffer("https://api.weixin.qq.com/sns/oauth2/access_token");
		getAccessTokenUrl.append("?appid=").append(Constant.WX_APPID).append("&secret=").append(Constant.WX_SECRET).append("&code=")
				.append(userCode).append("&grant_type=authorization_code");
		JSONObject jsonObject = HttpGetOrPost.sendGet(getAccessTokenUrl.toString());
		//判断是否正确获取到openid
		if(jsonObject.containsKey("openid")){
			logeer.info("微信认证后回调 GetOpenid :获取的openid为"+jsonObject.get("openid"));
			return (String) jsonObject.get("openid");	
		}else{
			logeer.warn("微信认证后回调 GetOpenid  :没有获取到openid");
			return "";
		}
		
	}	

}
